package com.bid.base.common.util.codec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

/**
 * <strong>Description : </strong> <br>
 * <p>
 * <strong>北京正源德标科技信息有限责任公司</strong> <br>
 * </p>
 * <br>
 *
 * @author : zhaots
 * @date Date : 2020年12月07日 18:22
 * 修改人 修改日期 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class Desede
{
  private static final String alg = "DESede";
  private static final String transformation = "DESede/CBC/PKCS5Padding";

  public static byte[] encode(byte[] src, String key, byte[] ivps)
    throws CodecException
  {
    return encode(src, key, ivps, "DESede/CBC/PKCS5Padding");
  }

  public static byte[] encode(byte[] src, String key, byte[] ivps, String transformation)
    throws CodecException
  {
    IvParameterSpec IvParameters;
    try
    {
      IvParameters = new IvParameterSpec(ivps);

      DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
      SecretKey securekey = keyFactory.generateSecret(dks);

      Cipher cipher = Cipher.getInstance(transformation);

      cipher.init(1, securekey, IvParameters);

      return cipher.doFinal(src);
    }
    catch (Exception e) {
      throw new CodecException(e);
    }
  }

  public static byte[] decode(byte[] src, String key, byte[] ivps)
    throws CodecException
  {
    return decode(src, key, ivps, "DESede/CBC/PKCS5Padding");
  }

  public static byte[] decode(byte[] src, String key, byte[] ivps, String transformation)
    throws CodecException
  {
    IvParameterSpec IvParameters;
    try
    {
      IvParameters = new IvParameterSpec(ivps);

      DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));

      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
      SecretKey securekey = keyFactory.generateSecret(dks);

      Cipher cipher = Cipher.getInstance(transformation);

      cipher.init(2, securekey, IvParameters);

      return cipher.doFinal(src);
    }
    catch (Exception e) {
      throw new CodecException(e);
    }
  }

  public static void main(String[] args) throws Exception
  {
    System.out.println(Base64.encode(encode("1qaz2ws".getBytes(), "01234567890123456789012345678912", "23456789".getBytes())));
    String decode = new String(decode(Base64.decode("uqtJiz1JMw4="), "111111112222222233333333", "12345678".getBytes()));
    System.out.println(decode);
  }
}